#include "wait_for_event.h"
#pragma comment(lib, "user32.lib")

// 全局停止事件
HANDLE STOP_EVENT = NULL;

void CWaitForEvent::create() {
  char event_name[50] = {0};
  DWORD pid = 0;
  pid = GetCurrentProcessId();

  if (STOP_EVENT == NULL) {
    wsprintfA(event_name, "stop_event_%d", pid); // 随机事件名
    STOP_EVENT = CreateEventA(NULL, TRUE, FALSE, event_name);
  }
}

// 恢复全局停止事件
void CWaitForEvent::start() { ResetEvent(STOP_EVENT); }

// 全局停止事件
void CWaitForEvent::stop() { SetEvent(STOP_EVENT); }

bool CWaitForEvent::need_run(int times) {
  if (WaitForSingleObject(STOP_EVENT, times) != WAIT_OBJECT_0) {
    return true;
  }
  return false;
}

void CWaitForEvent::close() {
  CloseHandle(STOP_EVENT);
  STOP_EVENT = NULL;
}
